package com.hy.filters;

import com.hy.common.utils.CookieUtils;
import com.hy.config.FilterProperties;
import com.hy.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xk.auth.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
@EnableConfigurationProperties({JwtProperties.class,FilterProperties.class})

public class AuthFilter extends ZuulFilter {

    @Autowired
    private JwtProperties prop;
    @Autowired
    private FilterProperties filterProperties;

    public String filterType() {

        //登录类型应该设置成前置过滤器
        return FilterConstants.PRE_TYPE;

    }
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;//过滤器顺序
    }

    public boolean shouldFilter() {//这是要不要过滤的一个方法
        boolean flag=true;
        //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取reques
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI();
        //遍历白名单集合
        List<String> allallowPaths = filterProperties.getAllowPaths();
        for (String path:allallowPaths){
            //然后比对uri中头部有没有包含白名单中的路径即可
            if (requestURI.startsWith(path)){//
                flag=false;//放行不拦截
                break;
            }

        }
        return flag;
    }
    public Object run() throws ZuulException {
         //获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取reques
        HttpServletRequest request = ctx.getRequest();
        //获取cookie中的token
        Cookie[] cookies = request.getCookies();
        String token = CookieUtils.getCookieValue(request,prop.getCookieName());
        try {
            //校验什么都不做即放行
            JwtUtils.getInfoFromToken(token, prop.getPublicKey());

        } catch (Exception e) {
            // 校验出现异常，返回403
            ctx.setSendZuulResponse(false);//拦截
            ctx.setResponseStatusCode(403);
        }
        // 校验权限  如果普通用户和管理员 此功能可以以后做
        return null;
    }
}
